{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "\n",
    "![GitHub](http://aliyuntianchipublic.cn-hangzhou.oss-pub.aliyun-inc.com/public/files/image/null/1532519441445_GEcsAYlvI8.jpg)\n",
    "\n",
    "\n",
    "<a id='HOME'></a>\n",
    "# Pandas基础\n",
    "\n",
    "* [1. 数据结构简介：DataFrame和Series](#Chapter1)\n",
    "* [2. 数据索引index](#Chapter2)\n",
    "* [3. 利用pandas查询数据](#Chapter3)\n",
    "* [4. 利用pandas的DataFrames进行统计分析](#Chapter4)\n",
    "* [5. 利用pandas实现SQL操作](#Chapter5)\n",
    "* [6. 利用pandas进行缺失值的处理](#Chapter6)\n",
    "* [7. 利用pandas实现Excel的数据透视表功能](#Chapter7)\n",
    "* [8. 多层索引的使用](#Chapter8)\n",
    "\n",
    "参考链接： https://www.cnblogs.com/nxld/p/6058591.html\n",
    "\n",
    "---\n",
    "<a id='Chapter1'></a>\n",
    "## 1. 数据结构简介\n",
    "[回目录](#HOME)\n",
    "\n",
    "在pandas中有两类非常重要的数据结构，即序列Series和数据框DataFrame。Series类似于numpy中的一维数组，除了通吃一维数组可用的函数或方法，而且其可通过索引标签的方式获取数据，还具有索引的自动对齐功能；DataFrame类似于numpy中的二维数组，同样可以通用numpy数组的函数和方法，而且还具有其他灵活应用，后续会介绍到"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 1.1 Series的创建\n",
    "\n",
    "序列的创建主要有三种方式：  \n",
    "\n",
    "**1）通过一维数组创建序列**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[0 1 2 3 4 5 6 7 8 9]\n"
     ]
    }
   ],
   "source": [
    "import numpy as np, pandas as pd\n",
    "\n",
    "arr1 = np.arange(10)\n",
    "print(arr1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "print(type(arr1))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    0\n",
      "1    1\n",
      "2    2\n",
      "3    3\n",
      "4    4\n",
      "5    5\n",
      "6    6\n",
      "7    7\n",
      "8    8\n",
      "9    9\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "s1 = pd.Series(arr1)\n",
    "print(s1)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'pandas.core.series.Series'>\n"
     ]
    }
   ],
   "source": [
    "print(type(s1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2）通过字典的方式创建序列**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': 10, 'b': 20, 'c': 30, 'd': 40, 'e': 50}\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "dic1 = {'a':10,'b':20,'c':30,'d':40,'e':50}\n",
    "print(dic1)\n",
    "print(type(dic1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**3）通过DataFrame中的某一行或某一列创建序列**"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1.2 DataFrame的创建\n",
    "\n",
    "数据框的创建主要有三种方式：  \n",
    "\n",
    "**1）通过二维数组创建数据框**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "[[ 0  1  2]\n",
      " [ 3  4  5]\n",
      " [ 6  7  8]\n",
      " [ 9 10 11]]\n",
      "<class 'numpy.ndarray'>\n"
     ]
    }
   ],
   "source": [
    "arr2 = np.array(np.arange(12)).reshape(4,3)\n",
    "print(arr2)\n",
    "print(type(arr2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   0   1   2\n",
      "0  0   1   2\n",
      "1  3   4   5\n",
      "2  6   7   8\n",
      "3  9  10  11\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "source": [
    "df1 = pd.DataFrame(arr2)\n",
    "print(df1)\n",
    "print(type(df1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2）通过字典的方式创建数据框**  \n",
    "以下以两种字典来创建数据框，一个是字典列表，一个是嵌套字典。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'a': [1, 2, 3, 4], 'b': [5, 6, 7, 8], 'c': [9, 10, 11, 12], 'd': [13, 14, 15, 16]}\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "dic2 = {'a':[1,2,3,4],'b':[5,6,7,8],'c':[9,10,11,12],'d':[13,14,15,16]}\n",
    "print(dic2)\n",
    "print(type(dic2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   a  b   c   d\n",
      "0  1  5   9  13\n",
      "1  2  6  10  14\n",
      "2  3  7  11  15\n",
      "3  4  8  12  16\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "source": [
    "df2 = pd.DataFrame(dic2)\n",
    "print(df2)\n",
    "print(type(df2))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{'one': {'a': 1, 'b': 2, 'c': 3, 'd': 4}, 'two': {'a': 5, 'b': 6, 'c': 7, 'd': 8}, 'three': {'a': 9, 'b': 10, 'c': 11, 'd': 12}}\n",
      "<class 'dict'>\n"
     ]
    }
   ],
   "source": [
    "dic3 = {'one':{'a':1,'b':2,'c':3,'d':4},'two':{'a':5,'b':6,'c':7,'d':8},'three':{'a':9,'b':10,'c':11,'d':12}}\n",
    "print(dic3)\n",
    "print(type(dic3))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   one  two  three\n",
      "a    1    5      9\n",
      "b    2    6     10\n",
      "c    3    7     11\n",
      "d    4    8     12\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "source": [
    "df3 = pd.DataFrame(dic3)\n",
    "print(df3)\n",
    "print(type(df3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**3）通过数据框的方式创建数据框** "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   one  three\n",
      "a    1      9\n",
      "b    2     10\n",
      "c    3     11\n",
      "d    4     12\n",
      "<class 'pandas.core.frame.DataFrame'>\n"
     ]
    }
   ],
   "source": [
    "df4 = df3[['one','three']]\n",
    "print(df4)\n",
    "print(type(df4))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1\n",
      "b    2\n",
      "c    3\n",
      "d    4\n",
      "Name: one, dtype: int64\n",
      "<class 'pandas.core.series.Series'>\n"
     ]
    }
   ],
   "source": [
    "s3 = df3['one']\n",
    "print(s3)\n",
    "print(type(s3))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter2'></a>\n",
    "## 2. 数据索引index\n",
    "[回目录](#HOME)\n",
    "\n",
    "细致的朋友可能会发现一个现象，不论是序列也好，还是数据框也好，对象的最左边总有一个非原始数据对象，这个是什么呢？不错，就是我们接下来要介绍的索引。\n",
    "在我看来，序列或数据框的索引有两大用处，一个是通过索引值或索引标签获取目标数据，另一个是通过索引，可以使序列或数据框的计算、操作实现自动化对齐，下面我们就来看看这两个功能的应用。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.1 通过索引值或索引标签获取数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0    1\n",
      "1    1\n",
      "2    2\n",
      "3    3\n",
      "4    5\n",
      "5    8\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "s4 = pd.Series(np.array([1,1,2,3,5,8]))\n",
    "print(s4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果不给序列一个指定的索引值，则序列自动生成一个从0开始的自增索引。可以通过index查看序列的索引："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "RangeIndex(start=0, stop=6, step=1)\n"
     ]
    }
   ],
   "source": [
    "print(s4.index)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在我们为序列设定一个自定义的索引值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    1\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    5\n",
      "f    8\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "s4.index = ['a','b','c','d','e','f']\n",
    "print(s4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "序列有了索引，就可以通过索引值或索引标签进行数据的获取："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "s4[3]:  3\n",
      "s4[e]:  5\n",
      "s4[1,3,5]: \n",
      "b    1\n",
      "d    3\n",
      "f    8\n",
      "dtype: int64\n",
      "s4[['a','b','d','f']]: \n",
      "a    1\n",
      "b    1\n",
      "d    3\n",
      "f    8\n",
      "dtype: int64\n",
      "s4[:4]: \n",
      "a    1\n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "dtype: int64\n",
      "s4['c':]: \n",
      "c    2\n",
      "d    3\n",
      "e    5\n",
      "f    8\n",
      "dtype: int64\n",
      "s4['b':'e']: \n",
      "b    1\n",
      "c    2\n",
      "d    3\n",
      "e    5\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print('s4[3]: ',s4[3])\n",
    "print('s4[e]: ',s4['e'])\n",
    "print(\"s4[1,3,5]: \")\n",
    "print(s4[[1,3,5]])\n",
    "print(\"s4[['a','b','d','f']]: \")\n",
    "print(s4[['a','b','d','f']])\n",
    "print('s4[:4]: ')\n",
    "print(s4[:4])\n",
    "print(\"s4['c':]: \")\n",
    "print(s4['c':])\n",
    "print(\"s4['b':'e']: \")\n",
    "print(s4['b':'e'])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "千万注意：如果通过索引标签获取数据的话，末端标签所对应的值是可以返回的！在一维数组中，就无法通过索引标签获取数据，这也是序列不同于一维数组的一个方面。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### 2.2 自动化对齐\n",
    "\n",
    "如果有两个序列，需要对这两个序列进行算术运算，这时索引的存在就体现的它的价值了—自动化对齐."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a    10\n",
      "b    15\n",
      "c    20\n",
      "d    30\n",
      "e    55\n",
      "f    80\n",
      "dtype: int64\n",
      "a    12\n",
      "c    11\n",
      "g    13\n",
      "b    15\n",
      "d    14\n",
      "f    16\n",
      "dtype: int64\n",
      "a    22.0\n",
      "b    30.0\n",
      "c    31.0\n",
      "d    44.0\n",
      "e     NaN\n",
      "f    96.0\n",
      "g     NaN\n",
      "dtype: float64\n",
      "a    0.833333\n",
      "b    1.000000\n",
      "c    1.818182\n",
      "d    2.142857\n",
      "e         NaN\n",
      "f    5.000000\n",
      "g         NaN\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "s5 = pd.Series(np.array([10,15,20,30,55,80]),index = ['a','b','c','d','e','f'])\n",
    "print(s5)\n",
    "\n",
    "s6 = pd.Series(np.array([12,11,13,15,14,16]),index = ['a','c','g','b','d','f'])\n",
    "print(s6)\n",
    "print(s5 + s6)\n",
    "print(s5/s6)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "由于s5中没有对应的g索引，s6中没有对应的e索引，所以数据的运算会产生两个缺失值NaN。注意，这里的算术结果就实现了两个序列索引的自动对齐，而非简单的将两个序列加总或相除。对于数据框的对齐，不仅仅是行索引的自动对齐，同时也会自动对齐列索引（变量名）\n",
    "\n",
    "数据框中同样有索引，而且数据框是二维数组的推广，所以其不仅有行索引，而且还存在列索引，关于数据框中的索引相比于序列的应用要强大的多，这部分内容将放在数据查询中讲解。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter3'></a>\n",
    "## 3. 利用pandas查询数据\n",
    "[回目录](#HOME)\n",
    "\n",
    "\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这里的查询数据相当于R语言里的subset功能，可以通过布尔索引有针对的选取原数据的子集、指定行、指定列等。我们先导入一个student数据集"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [],
   "source": [
    "import pandas as pd\n",
    "\n",
    "stu_dic = {'Age':[14,13,13,14,14,12,12,15,13,12,11,14,12,15,16,12,15,11,15],\n",
    "'Height':[69,56.5,65.3,62.8,63.5,57.3,59.8,62.5,62.5,59,51.3,64.3,56.3,66.5,72,64.8,67,57.5,66.5],\n",
    "'Name':['Alfred','Alice','Barbara','Carol','Henry','James','Jane','Janet','Jeffrey','John','Joyce','Judy','Louise','Marry','Philip','Robert','Ronald','Thomas','Willam'],\n",
    "'Sex':['M','F','F','F','M','M','F','F','M','M','F','F','F','F','M','M','M','M','M'],\n",
    "'Weight':[112.5,84,98,102.5,102.5,83,84.5,112.5,84,99.5,50.5,90,77,112,150,128,133,85,112]}\n",
    "student = pd.DataFrame(stu_dic)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查询数据的前5行或末尾5行**  \n",
    "\n",
    "student.head()  \n",
    "student.tail()  "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age  Height     Name Sex  Weight\n",
      "0   14    69.0   Alfred   M   112.5\n",
      "1   13    56.5    Alice   F    84.0\n",
      "2   13    65.3  Barbara   F    98.0\n",
      "3   14    62.8    Carol   F   102.5\n",
      "4   14    63.5    Henry   M   102.5\n"
     ]
    }
   ],
   "source": [
    "print(student.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 27,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height    Name Sex  Weight\n",
      "14   16    72.0  Philip   M   150.0\n",
      "15   12    64.8  Robert   M   128.0\n",
      "16   15    67.0  Ronald   M   133.0\n",
      "17   11    57.5  Thomas   M    85.0\n",
      "18   15    66.5  Willam   M   112.0\n"
     ]
    }
   ],
   "source": [
    "print(student.tail())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查询指定的行**  \n",
    "\n",
    "student.loc[[0,2,4,5,7]] #这里的loc索引标签函数必须是中括号[]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 28,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age  Height     Name Sex  Weight\n",
      "0   14    69.0   Alfred   M   112.5\n",
      "2   13    65.3  Barbara   F    98.0\n",
      "4   14    63.5    Henry   M   102.5\n",
      "5   12    57.3    James   M    83.0\n",
      "7   15    62.5    Janet   F   112.5\n"
     ]
    }
   ],
   "source": [
    "print(student.loc[[0,2,4,5,7]])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查询指定的列**\n",
    "\n",
    "student[['Name','Height','Weight']].head() #如果多个列的话，必须使用双重中括号"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 29,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      Name  Height  Weight\n",
      "0   Alfred    69.0   112.5\n",
      "1    Alice    56.5    84.0\n",
      "2  Barbara    65.3    98.0\n",
      "3    Carol    62.8   102.5\n",
      "4    Henry    63.5   102.5\n"
     ]
    }
   ],
   "source": [
    "print(student[['Name','Height','Weight']].head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**也可以通过loc索引标签查询指定的列**\n",
    "\n",
    "student.loc[:,['Name','Height','Weight']].head()"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 30,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      Name  Height  Weight\n",
      "0   Alfred    69.0   112.5\n",
      "1    Alice    56.5    84.0\n",
      "2  Barbara    65.3    98.0\n",
      "3    Carol    62.8   102.5\n",
      "4    Henry    63.5   102.5\n"
     ]
    }
   ],
   "source": [
    "print(student.loc[:,['Name','Height','Weight']].head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查询出所有12岁以上的女生信息**\n",
    "\n",
    "student[(student['Sex']=='F') & (student['Age']>12)]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 31,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height     Name Sex  Weight\n",
      "1    13    56.5    Alice   F    84.0\n",
      "2    13    65.3  Barbara   F    98.0\n",
      "3    14    62.8    Carol   F   102.5\n",
      "7    15    62.5    Janet   F   112.5\n",
      "11   14    64.3     Judy   F    90.0\n",
      "13   15    66.5    Marry   F   112.0\n"
     ]
    }
   ],
   "source": [
    "print(student[(student['Sex']=='F') & (student['Age']>12)])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**查询出所有12岁以上的女生姓名、身高和体重**\n",
    "\n",
    "student[(student['Sex']=='F') & (student['Age']>12)][['Name','Height','Weight']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 32,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "       Name  Height  Weight\n",
      "1     Alice    56.5    84.0\n",
      "2   Barbara    65.3    98.0\n",
      "3     Carol    62.8   102.5\n",
      "7     Janet    62.5   112.5\n",
      "11     Judy    64.3    90.0\n",
      "13    Marry    66.5   112.0\n"
     ]
    }
   ],
   "source": [
    "print(student[(student['Sex']=='F') & (student['Age']>12)][['Name','Height','Weight']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "上面的查询逻辑其实非常的简单，需要注意的是，如果是多个条件的查询，必须在&（且）或者|（或）的两端条件用括号括起来。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter4'></a>\n",
    "## 4. 利用pandas的DataFrames进行统计分析\n",
    "[回目录](#HOME)\n",
    "\n",
    "pandas模块为我们提供了非常多的描述性统计分析的指标函数，如总和、均值、最小值、最大值等，我们来具体看看这些函数：\n",
    "首先随机生成三组数据"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 33,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "非空元素计算:  100\n",
      "最小值:  -4.1270333212494705\n",
      "最大值:  7.781921030926066\n",
      "最小值的位置:  81\n",
      "最大值的位置:  39\n",
      "10%分位数:  0.6870184644069928\n",
      "求和:  307.0224566250873\n",
      "均值:  3.070224566250873\n",
      "中位数:  3.204555266776845\n",
      "众数:  0    -4.127033\n",
      "1    -1.800907\n",
      "2    -1.485370\n",
      "3    -1.149955\n",
      "4    -1.042510\n",
      "        ...   \n",
      "95    5.865414\n",
      "96    6.091318\n",
      "97    7.015686\n",
      "98    7.061207\n",
      "99    7.781921\n",
      "Length: 100, dtype: float64\n",
      "方差:  4.005609378535087\n",
      "标准差:  2.001401853335578\n",
      "平均绝对偏差:  1.5112880411556104\n",
      "偏度:  -0.6494780760484293\n",
      "峰度:  1.2201094052398012\n",
      "描述性统计指标:  count    100.000000\n",
      "mean       3.070225\n",
      "std        2.001402\n",
      "min       -4.127033\n",
      "25%        2.040101\n",
      "50%        3.204555\n",
      "75%        4.434788\n",
      "max        7.781921\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "np.random.seed(1234)\n",
    "d1 = pd.Series(2*np.random.normal(size = 100)+3)\n",
    "d2 = np.random.f(2,4,size = 100)\n",
    "d3 = np.random.randint(1,100,size = 100)\n",
    "\n",
    "print('非空元素计算: ', d1.count()) #非空元素计算\n",
    "print('最小值: ', d1.min()) #最小值\n",
    "print('最大值: ', d1.max()) #最大值\n",
    "print('最小值的位置: ', d1.idxmin()) #最小值的位置，类似于R中的which.min函数\n",
    "print('最大值的位置: ', d1.idxmax()) #最大值的位置，类似于R中的which.max函数\n",
    "print('10%分位数: ', d1.quantile(0.1)) #10%分位数\n",
    "print('求和: ', d1.sum()) #求和\n",
    "print('均值: ', d1.mean()) #均值\n",
    "print('中位数: ', d1.median()) #中位数\n",
    "print('众数: ', d1.mode()) #众数\n",
    "print('方差: ', d1.var()) #方差\n",
    "print('标准差: ', d1.std()) #标准差\n",
    "print('平均绝对偏差: ', d1.mad()) #平均绝对偏差\n",
    "print('偏度: ', d1.skew()) #偏度\n",
    "print('峰度: ', d1.kurt()) #峰度\n",
    "print('描述性统计指标: ', d1.describe()) #一次性输出多个描述性统计指标"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "必须注意的是，descirbe方法只能针对序列或数据框，一维数组是没有这个方法的\n",
    "\n",
    "这里自定义一个函数，将这些统计描述指标全部汇总到一起:\n",
    "\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 36,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Count        100.000000\n",
      "Min           -4.127033\n",
      "Whicn_Min     81.000000\n",
      "Q1             2.040101\n",
      "Median         3.204555\n",
      "Q3             4.434788\n",
      "Mean           3.070225\n",
      "Max            7.781921\n",
      "Which_Max     39.000000\n",
      "Mad            1.511288\n",
      "Var            4.005609\n",
      "Std            2.001402\n",
      "Skew          -0.649478\n",
      "Kurt           1.220109\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "def stats(x):\n",
    "\treturn pd.Series([x.count(),x.min(),x.idxmin(),x.quantile(.25),x.median(),x.quantile(.75),\n",
    "                      x.mean(),x.max(),x.idxmax(),x.mad(),x.var(),x.std(),x.skew(),x.kurt()],\n",
    "                     index = ['Count','Min','Whicn_Min','Q1','Median','Q3','Mean','Max',\n",
    "                              'Which_Max','Mad','Var','Std','Skew','Kurt'])\n",
    "print(stats(d1))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在实际的工作中，我们可能需要处理的是一系列的数值型数据框，如何将这个函数应用到数据框中的每一列呢？可以使用apply函数，这个非常类似于R中的apply的应用方法。\n",
    "将之前创建的d1,d2,d3数据构建数据框:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 37,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         x1        x2    x3\n",
      "0  3.942870  1.369531  55.0\n",
      "1  0.618049  0.943264  68.0\n",
      "2  5.865414  0.590663  73.0\n",
      "3  2.374696  0.206548  59.0\n",
      "4  1.558823  0.223204  60.0\n"
     ]
    }
   ],
   "source": [
    "df = pd.DataFrame(np.array([d1,d2,d3]).T,columns=['x1','x2','x3'])\n",
    "print(df.head())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 38,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "                   x1          x2          x3\n",
      "Count      100.000000  100.000000  100.000000\n",
      "Min         -4.127033    0.014330    3.000000\n",
      "Whicn_Min   81.000000   72.000000   76.000000\n",
      "Q1           2.040101    0.249580   25.000000\n",
      "Median       3.204555    1.000613   54.500000\n",
      "Q3           4.434788    2.101581   73.000000\n",
      "Mean         3.070225    2.028608   51.490000\n",
      "Max          7.781921   18.791565   98.000000\n",
      "Which_Max   39.000000   53.000000   96.000000\n",
      "Mad          1.511288    1.922669   24.010800\n",
      "Var          4.005609   10.206447  780.090808\n",
      "Std          2.001402    3.194753   27.930106\n",
      "Skew        -0.649478    3.326246   -0.118917\n",
      "Kurt         1.220109   12.636286   -1.211579\n"
     ]
    }
   ],
   "source": [
    "print(df.apply(stats))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "非常完美，就这样很简单的创建了数值型数据的统计性描述。如果是离散型数据呢？就不能用这个统计口径了，我们需要统计离散变量的观测数、唯一值个数、众数水平及个数。你只需要使用describe方法就可以实现这样的统计了"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 39,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "count     19\n",
      "unique     2\n",
      "top        M\n",
      "freq      10\n",
      "Name: Sex, dtype: object\n"
     ]
    }
   ],
   "source": [
    "print(student['Sex'].describe())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "除以上的简单描述性统计之外，还提供了连续变量的相关系数（corr）和协方差矩阵（cov）的求解，这个跟R语言是一致的用法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 40,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          x1        x2        x3\n",
      "x1  1.000000  0.136085  0.037185\n",
      "x2  0.136085  1.000000 -0.005688\n",
      "x3  0.037185 -0.005688  1.000000\n"
     ]
    }
   ],
   "source": [
    "print(df.corr())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "关于相关系数的计算可以调用pearson方法或kendell方法或spearman方法，默认使用pearson方法。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 41,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "         x1        x2        x3\n",
      "x1  1.00000  0.178950  0.006590\n",
      "x2  0.17895  1.000000 -0.033874\n",
      "x3  0.00659 -0.033874  1.000000\n"
     ]
    }
   ],
   "source": [
    "print(df.corr('spearman'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果只想关注某一个变量与其余变量的相关系数的话，可以使用corrwith,如下方只关心x1与其余变量的相关系数:"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 42,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "x1    1.000000\n",
      "x2    0.136085\n",
      "x3    0.037185\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print(df.corrwith(df['x1']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "数值型变量间的协方差矩阵"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 43,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "          x1         x2          x3\n",
      "x1  4.005609   0.870124    2.078596\n",
      "x2  0.870124  10.206447   -0.507512\n",
      "x3  2.078596  -0.507512  780.090808\n"
     ]
    }
   ],
   "source": [
    "print(df.cov())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter5'></a>\n",
    "## 5. 利用pandas实现SQL操作\n",
    "[回目录](#HOME)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在SQL中常见的操作主要是增、删、改、查几个动作，那么pandas能否实现对数据的这几项操作呢？答案是Of Course!\n",
    "\n",
    "**增：添加新行或增加新列**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           Name Sex  Age  Height  Weight\n",
      "0  LiuShunxiang   M   27   165.7      61\n",
      "1     Zhangshan   F   23   167.2      63\n"
     ]
    }
   ],
   "source": [
    "dic = {'Name':['LiuShunxiang','Zhangshan'],'Sex':['M','F'],'Age':[27,23],'Height':[165.7,167.2],'Weight':[61,63]}\n",
    "student2 = pd.DataFrame(dic)\n",
    "print(student2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在将student2中的数据新增到student中，可以通过concat函数实现："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height          Name Sex  Weight\n",
      "0    14    69.0        Alfred   M   112.5\n",
      "1    13    56.5         Alice   F    84.0\n",
      "2    13    65.3       Barbara   F    98.0\n",
      "3    14    62.8         Carol   F   102.5\n",
      "4    14    63.5         Henry   M   102.5\n",
      "5    12    57.3         James   M    83.0\n",
      "6    12    59.8          Jane   F    84.5\n",
      "7    15    62.5         Janet   F   112.5\n",
      "8    13    62.5       Jeffrey   M    84.0\n",
      "9    12    59.0          John   M    99.5\n",
      "10   11    51.3         Joyce   F    50.5\n",
      "11   14    64.3          Judy   F    90.0\n",
      "12   12    56.3        Louise   F    77.0\n",
      "13   15    66.5         Marry   F   112.0\n",
      "14   16    72.0        Philip   M   150.0\n",
      "15   12    64.8        Robert   M   128.0\n",
      "16   15    67.0        Ronald   M   133.0\n",
      "17   11    57.5        Thomas   M    85.0\n",
      "18   15    66.5        Willam   M   112.0\n",
      "0    27   165.7  LiuShunxiang   M    61.0\n",
      "1    23   167.2     Zhangshan   F    63.0\n"
     ]
    }
   ],
   "source": [
    "student3 = pd.concat([student,student2])\n",
    "print(student3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意到了吗？在数据库中union必须要求两张表的列顺序一致，而这里concat函数可以自动对齐两个数据框的变量！\n",
    "\n",
    "新增列的话，其实在pandas中就更简单了，例如在student2中新增一列学生成绩："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age  Height          Name Sex  Weight  Score\n",
      "0   27   165.7  LiuShunxiang   M      61    NaN\n",
      "1   23   167.2     Zhangshan   F      63    NaN\n"
     ]
    }
   ],
   "source": [
    "print(pd.DataFrame(student2, columns=['Age','Height','Name','Sex','Weight','Score']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对于新增的列没有赋值，就会出现空NaN的形式。\n",
    "\n",
    "**删：删除表、观测行或变量列**  \n",
    "删除数据框student2,通过del命令实现，该命令可以删除Python的所有对象。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "ename": "NameError",
     "evalue": "name 'student2' is not defined",
     "output_type": "error",
     "traceback": [
      "\u001b[0;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m                                 Traceback (most recent call last)",
      "\u001b[0;32m<ipython-input-7-3453d237c14b>\u001b[0m in \u001b[0;36m<module>\u001b[0;34m\u001b[0m\n\u001b[1;32m      1\u001b[0m \u001b[0;32mdel\u001b[0m \u001b[0mstudent2\u001b[0m \u001b[0;31m#删除数据框student2, 通过del命令可以删除python的所有对象\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0;32m----> 2\u001b[0;31m \u001b[0mprint\u001b[0m\u001b[0;34m(\u001b[0m\u001b[0mstudent2\u001b[0m\u001b[0;34m)\u001b[0m\u001b[0;34m\u001b[0m\u001b[0m\n\u001b[0m",
      "\u001b[0;31mNameError\u001b[0m: name 'student2' is not defined"
     ]
    }
   ],
   "source": [
    "del student2 #删除数据框student2, 通过del命令可以删除python的所有对象\n",
    "print(student2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "删除指定的行"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height     Name Sex  Weight\n",
      "2    13    65.3  Barbara   F    98.0\n",
      "4    14    63.5    Henry   M   102.5\n",
      "5    12    57.3    James   M    83.0\n",
      "7    15    62.5    Janet   F   112.5\n",
      "8    13    62.5  Jeffrey   M    84.0\n",
      "9    12    59.0     John   M    99.5\n",
      "10   11    51.3    Joyce   F    50.5\n",
      "11   14    64.3     Judy   F    90.0\n",
      "12   12    56.3   Louise   F    77.0\n",
      "13   15    66.5    Marry   F   112.0\n",
      "14   16    72.0   Philip   M   150.0\n",
      "15   12    64.8   Robert   M   128.0\n",
      "16   15    67.0   Ronald   M   133.0\n",
      "17   11    57.5   Thomas   M    85.0\n",
      "18   15    66.5   Willam   M   112.0\n"
     ]
    }
   ],
   "source": [
    "print(student.drop([0,1,3,6]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "原数据中的第1,2,4,7行的数据已经被删除了。  \n",
    "\n",
    "根据布尔索引删除行数据，其实这个删除就是保留删除条件的反面数据，例如删除所有14岁以下的学生："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height    Name Sex  Weight\n",
      "7    15    62.5   Janet   F   112.5\n",
      "13   15    66.5   Marry   F   112.0\n",
      "14   16    72.0  Philip   M   150.0\n",
      "16   15    67.0  Ronald   M   133.0\n",
      "18   15    66.5  Willam   M   112.0\n"
     ]
    }
   ],
   "source": [
    "print(student[student['Age']>14])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "删除指定的列 "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age     Name Sex\n",
      "0   14   Alfred   M\n",
      "1   13    Alice   F\n",
      "2   13  Barbara   F\n",
      "3   14    Carol   F\n",
      "4   14    Henry   M\n"
     ]
    }
   ],
   "source": [
    "print(student.drop(['Height','Weight'],axis=1).head())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们发现，不论是删除行还是删除列，都可以通过drop方法实现，只需要设定好删除的轴即可，即调整drop方法中的axis参数。默认该参数为0，表示删除行观测，如果需要删除列变量，则需设置为1。\n",
    "\n",
    "**改：修改原始记录的值**  \n",
    "\n",
    "如果发现表中的某些数据错误了，如何更改原来的值呢？我们试试结合布尔索引和赋值的方法：\n",
    "例如发现student3中姓名为LiuShunxiang的学生身高错了，应该是173，如何改呢？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           Name  Height\n",
      "0  LiuShunxiang   173.0\n"
     ]
    }
   ],
   "source": [
    "student3.loc[student3['Name'] == 'LiuShunxiang','Height']=173\n",
    "print(student3[student3['Name'] == 'LiuShunxiang'][['Name','Height']])"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这样就可以把原来的身高修改为现在的170了。\n",
    "看，关于索引的操作非常灵活、方便吧，就这样轻松搞定数据的更改。\n",
    "\n",
    "**查：有关数据查询部分，上面已经介绍过**\n",
    "\n",
    "下面重点讲讲聚合、排序和多表连接操作。\n",
    "\n",
    "**聚合：pandas模块中可以通过groupby()函数实现数据的聚合操作**\n",
    "\n",
    "根据性别分组，计算各组别中学生身高和体重的平均值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "           Age     Height      Weight\n",
      "Sex                                  \n",
      "F    13.222222  60.588889   90.111111\n",
      "M    13.400000  63.910000  108.950000\n"
     ]
    }
   ],
   "source": [
    "print(student.groupby('Sex').mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "如果不对原始数据作限制的话，聚合函数会自动选择数值型数据进行聚合计算。如果不想对年龄计算平均值的话，就需要剔除改变量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "        Height      Weight\n",
      "Sex                       \n",
      "F    60.588889   90.111111\n",
      "M    63.910000  108.950000\n"
     ]
    }
   ],
   "source": [
    "print(student.drop('Age',axis=1).groupby('Sex').mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "groupby还可以使用多个分组变量，例如根本年龄和性别分组，计算身高与体重的平均值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "            Height  Weight\n",
      "Sex Age                   \n",
      "F   11   51.300000   50.50\n",
      "    12   58.050000   80.75\n",
      "    13   60.900000   91.00\n",
      "    14   63.550000   96.25\n",
      "    15   64.500000  112.25\n",
      "M   11   57.500000   85.00\n",
      "    12   60.366667  103.50\n",
      "    13   62.500000   84.00\n",
      "    14   66.250000  107.50\n",
      "    15   66.750000  122.50\n",
      "    16   72.000000  150.00\n"
     ]
    }
   ],
   "source": [
    "print(student.groupby(['Sex','Age']).mean())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "当然，还可以对每个分组计算多个统计量："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "        Height             Weight        \n",
      "          mean median        mean  median\n",
      "Sex                                      \n",
      "F    60.588889  62.50   90.111111   90.00\n",
      "M    63.910000  64.15  108.950000  107.25\n"
     ]
    }
   ],
   "source": [
    "print(student.drop('Age',axis=1).groupby('Sex').agg([np.mean,np.median]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**排序：**  \n",
    "\n",
    "排序在日常的统计分析中还是比较常见的操作，我们可以使用sort_index和sort_values实现序列和数据框的排序工作："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     3\n",
      "1    11\n",
      "2     5\n",
      "3    12\n",
      "4    16\n",
      "5     9\n",
      "6    13\n",
      "7    17\n",
      "8    14\n",
      "9    15\n",
      "dtype: int64\n",
      "0     3\n",
      "1    11\n",
      "2     5\n",
      "3    12\n",
      "4    16\n",
      "5     9\n",
      "6    13\n",
      "7    17\n",
      "8    14\n",
      "9    15\n",
      "dtype: int64\n",
      "7    17\n",
      "4    16\n",
      "9    15\n",
      "8    14\n",
      "6    13\n",
      "3    12\n",
      "1    11\n",
      "5     9\n",
      "2     5\n",
      "0     3\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "Data = pd.Series(np.array(np.random.randint(1,20,10)))\n",
    "print(Data)\n",
    "print(Data.sort_index())\n",
    "print(Data.sort_values(ascending=False))\n"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "在数据框中一般都是按值排序，  \n",
    "例如："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height     Name Sex  Weight\n",
      "10   11    51.3    Joyce   F    50.5\n",
      "17   11    57.5   Thomas   M    85.0\n",
      "12   12    56.3   Louise   F    77.0\n",
      "5    12    57.3    James   M    83.0\n",
      "9    12    59.0     John   M    99.5\n",
      "6    12    59.8     Jane   F    84.5\n",
      "15   12    64.8   Robert   M   128.0\n",
      "1    13    56.5    Alice   F    84.0\n",
      "8    13    62.5  Jeffrey   M    84.0\n",
      "2    13    65.3  Barbara   F    98.0\n",
      "3    14    62.8    Carol   F   102.5\n",
      "4    14    63.5    Henry   M   102.5\n",
      "11   14    64.3     Judy   F    90.0\n",
      "0    14    69.0   Alfred   M   112.5\n",
      "7    15    62.5    Janet   F   112.5\n",
      "13   15    66.5    Marry   F   112.0\n",
      "18   15    66.5   Willam   M   112.0\n",
      "16   15    67.0   Ronald   M   133.0\n",
      "14   16    72.0   Philip   M   150.0\n"
     ]
    }
   ],
   "source": [
    "print(student.sort_values(by = ['Age','Height']))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**多表连接:**   \n",
    "\n",
    "多表之间的连接也是非常常见的数据库操作，连接分内连接和外连接，在数据库语言中通过join关键字实现，pandas我比较建议使用merge函数实现数据的各种连接操作。\n",
    "如下是构造一张学生的成绩表："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "      Name  Score\n",
      "0   Alfred     88\n",
      "1    Alice     76\n",
      "2  Barbara     89\n",
      "3    Carol     67\n",
      "4    Henry     79\n",
      "5  Jeffrey     90\n",
      "6     Judy     92\n",
      "7   Philip     86\n",
      "8   Robert     73\n",
      "9   Willam     77\n"
     ]
    }
   ],
   "source": [
    "dic2 = {'Name':['Alfred','Alice','Barbara','Carol','Henry','Jeffrey','Judy','Philip','Robert','Willam'],\n",
    "        'Score':[88,76,89,67,79,90,92,86,73,77]}\n",
    "score = pd.DataFrame(dic2)\n",
    "\n",
    "print(score)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "现在想把学生表student与学生成绩表score做一个关联，该如何操作呢？"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "   Age  Height     Name Sex  Weight  Score\n",
      "0   14    69.0   Alfred   M   112.5     88\n",
      "1   13    56.5    Alice   F    84.0     76\n",
      "2   13    65.3  Barbara   F    98.0     89\n",
      "3   14    62.8    Carol   F   102.5     67\n",
      "4   14    63.5    Henry   M   102.5     79\n",
      "5   13    62.5  Jeffrey   M    84.0     90\n",
      "6   14    64.3     Judy   F    90.0     92\n",
      "7   16    72.0   Philip   M   150.0     86\n",
      "8   12    64.8   Robert   M   128.0     73\n",
      "9   15    66.5   Willam   M   112.0     77\n"
     ]
    }
   ],
   "source": [
    "stu_score1 = pd.merge(student, score, on='Name')\n",
    "print(stu_score1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "注意，默认情况下，merge函数实现的是两个表之间的内连接，即返回两张表中共同部分的数据。可以通过how参数设置连接的方式，left为左连接；right为右连接；outer为外连接。"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "    Age  Height     Name Sex  Weight  Score\n",
      "0    14    69.0   Alfred   M   112.5   88.0\n",
      "1    13    56.5    Alice   F    84.0   76.0\n",
      "2    13    65.3  Barbara   F    98.0   89.0\n",
      "3    14    62.8    Carol   F   102.5   67.0\n",
      "4    14    63.5    Henry   M   102.5   79.0\n",
      "5    12    57.3    James   M    83.0    NaN\n",
      "6    12    59.8     Jane   F    84.5    NaN\n",
      "7    15    62.5    Janet   F   112.5    NaN\n",
      "8    13    62.5  Jeffrey   M    84.0   90.0\n",
      "9    12    59.0     John   M    99.5    NaN\n",
      "10   11    51.3    Joyce   F    50.5    NaN\n",
      "11   14    64.3     Judy   F    90.0   92.0\n",
      "12   12    56.3   Louise   F    77.0    NaN\n",
      "13   15    66.5    Marry   F   112.0    NaN\n",
      "14   16    72.0   Philip   M   150.0   86.0\n",
      "15   12    64.8   Robert   M   128.0   73.0\n",
      "16   15    67.0   Ronald   M   133.0    NaN\n",
      "17   11    57.5   Thomas   M    85.0    NaN\n",
      "18   15    66.5   Willam   M   112.0   77.0\n"
     ]
    }
   ],
   "source": [
    "stu_score2 = pd.merge(student, score, on='Name', how='left')\n",
    "print(stu_score2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "左连接实现的是保留student表中的所有信息，同时将score表的信息与之配对，能配多少配多少，对于没有配对上的Name，将会显示成绩为NaN。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter6'></a>\n",
    "## 6. 利用pandas进行缺失值的处理\n",
    "[回目录](#HOME)\n",
    "\n",
    "现实生活中的数据是非常杂乱的，其中缺失值也是非常常见的，对于缺失值的存在可能会影响到后期的数据分析或挖掘工作，那么我们该如何处理这些缺失值呢？  \n",
    "常用的有三大类方法，即删除法、填补法和插值法。  \n",
    "* **删除法：**当数据中的某个变量大部分值都是缺失值，可以考虑删除改变量；当缺失值是随机分布的，且缺失的数量并不是很多是，也可以删除这些缺失的观测。  \n",
    "* **替补法：**对于连续型变量，如果变量的分布近似或就是正态分布的话，可以用均值替代那些缺失值；如果变量是有偏的，可以使用中位数来代替那些缺失值；对于离散型变量，我们一般用众数去替换那些存在缺失的观测。  \n",
    "* **插补法：**插补法是基于蒙特卡洛模拟法，结合线性模型、广义线性模型、决策树等方法计算出来的预测值替换缺失值。\n",
    "\n",
    "我们这里就介绍简单的删除法和替补法："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     88.0\n",
      "1     76.0\n",
      "2     89.0\n",
      "3     67.0\n",
      "4     79.0\n",
      "5      NaN\n",
      "6      NaN\n",
      "7      NaN\n",
      "8     90.0\n",
      "9      NaN\n",
      "10     NaN\n",
      "11    92.0\n",
      "12     NaN\n",
      "13     NaN\n",
      "14    86.0\n",
      "15    73.0\n",
      "16     NaN\n",
      "17     NaN\n",
      "18    77.0\n",
      "Name: Score, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "s = stu_score2['Score']\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "这是一组含有缺失值的序列，我们可以结合sum函数和isnull函数来检测数据中含有多少缺失值："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "9\n"
     ]
    }
   ],
   "source": [
    "print(sum(pd.isnull(s)))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "直接删除缺失值"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "0     88.0\n",
      "1     76.0\n",
      "2     89.0\n",
      "3     67.0\n",
      "4     79.0\n",
      "8     90.0\n",
      "11    92.0\n",
      "14    86.0\n",
      "15    73.0\n",
      "18    77.0\n",
      "Name: Score, dtype: float64\n"
     ]
    }
   ],
   "source": [
    "print(s.dropna())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "默认情况下，dropna会删除任何含有缺失值的行，我们再构造一个数据框试试："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "1   3.0   5.0   NaN\n",
      "2  13.0  21.0  34.0\n",
      "3  55.0   NaN  10.0\n",
      "4   NaN   NaN   NaN\n",
      "5   NaN   1.0   2.0\n",
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "2  13.0  21.0  34.0\n"
     ]
    }
   ],
   "source": [
    "df = pd.DataFrame([[1,1,2],[3,5,np.nan],[13,21,34],[55,np.nan,10],[np.nan,np.nan,np.nan],[np.nan,1,2]],columns=('x1','x2','x3'))\n",
    "print(df)\n",
    "print(df.dropna())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "返回结果表明，数据中只要含有缺失值NaN,该数据行就会被删除，如果使用参数how=’all’，则表明只删除所有行为缺失值的观测;\n",
    "\n",
    "使用一个常量来填补缺失值，可以使用fillna函数实现简单的填补工作：  \n",
    "**1）用0填补所有缺失值**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "1   3.0   5.0   0.0\n",
      "2  13.0  21.0  34.0\n",
      "3  55.0   0.0  10.0\n",
      "4   0.0   0.0   0.0\n",
      "5   0.0   1.0   2.0\n"
     ]
    }
   ],
   "source": [
    "print(df.fillna(0))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**2)采用前项填充或后向填充**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "1   3.0   5.0   2.0\n",
      "2  13.0  21.0  34.0\n",
      "3  55.0  21.0  10.0\n",
      "4  55.0  21.0  10.0\n",
      "5  55.0   1.0   2.0\n",
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "1   3.0   5.0  34.0\n",
      "2  13.0  21.0  34.0\n",
      "3  55.0   1.0  10.0\n",
      "4   NaN   1.0   2.0\n",
      "5   NaN   1.0   2.0\n"
     ]
    }
   ],
   "source": [
    "print(df.fillna(method='ffill'))\n",
    "print(df.fillna(method='bfill'))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**3)使用常量填充不同的列**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "1   3.0   5.0   3.0\n",
      "2  13.0  21.0  34.0\n",
      "3  55.0   2.0  10.0\n",
      "4   1.0   2.0   3.0\n",
      "5   1.0   1.0   2.0\n"
     ]
    }
   ],
   "source": [
    "print(df.fillna({'x1':1,'x2':2,'x3':3}))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "8.0\n",
      "7.0\n",
      "12.0\n",
      "     x1    x2    x3\n",
      "0   1.0   1.0   2.0\n",
      "1   3.0   5.0  12.0\n",
      "2  13.0  21.0  34.0\n",
      "3  55.0   7.0  10.0\n",
      "4   8.0   7.0  12.0\n",
      "5   8.0   1.0   2.0\n"
     ]
    }
   ],
   "source": [
    "x1_median=df['x1'].median()\n",
    "x2_mean=df['x2'].mean()\n",
    "x3_mean=df['x3'].mean()\n",
    "\n",
    "print(x1_median)\n",
    "print(x2_mean)\n",
    "print(x3_mean)\n",
    "print(df.fillna({'x1':x1_median,'x2':x2_mean,'x3':x3_mean}))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "很显然，在使用填充法时，相对于常数填充或前项、后项填充，使用各列的众数、均值或中位数填充要更加合理一点，这也是工作中常用的一个快捷手段。"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter7'></a>\n",
    "## 7. 利用pandas实现Excel的数据透视表功能\n",
    "[回目录](#HOME)\n",
    "\n",
    "在Excel中有一个非常强大的功能就是数据透视表，通过托拉拽的方式可以迅速的查看数据的聚合情况，这里的聚合可以是计数、求和、均值、标准差等。\n",
    "pandas为我们提供了非常强大的函数pivot_table()，该函数就是实现数据透视表功能的。对于上面所说的一些聚合函数，可以通过参数aggfunc设定。我们先看看这个函数的语法和参数吧："
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "```python\n",
    "pivot_table(data,values=None,\n",
    "            index=None,\n",
    "            columns=None,\n",
    "            aggfunc='mean',\n",
    "            fill_value=None,\n",
    "            margins=False,\n",
    "            dropna=True,\n",
    "            margins_name='All')  \n",
    "```\n",
    "data：需要进行数据透视表操作的数据框  \n",
    "values：指定需要聚合的字段   \n",
    "index：指定某些原始变量作为行索引  \n",
    "columns：指定哪些离散的分组变量  \n",
    "aggfunc：指定相应的聚合函数   \n",
    "fill_value：使用一个常数替代缺失值，默认不替换   \n",
    "margins：是否进行行或列的汇总，默认不汇总    \n",
    "dropna：默认所有观测为缺失的列   \n",
    "margins_name：默认行汇总或列汇总的名称为'All'"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们仍然以student表为例，来认识一下数据透视表pivot_table函数的用法：\n",
    "对一个分组变量（Sex），一个数值变量（Height）作统计汇总"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sex             F      M\n",
      "Height  60.588889  63.91\n"
     ]
    }
   ],
   "source": [
    "Table1 = pd.pivot_table(student, values=['Height'], columns=['Sex'])\n",
    "print(Table1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对一个分组变量（Sex），两个数值变量（Height,Weight）作统计汇总"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sex             F       M\n",
      "Height  60.588889   63.91\n",
      "Weight  90.111111  108.95\n"
     ]
    }
   ],
   "source": [
    "Table2 = pd.pivot_table(student, values=['Height','Weight'], columns=['Sex'])\n",
    "print(Table2)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "对两个分组变量（Sex，Age)，两个数值变量（Height,Weight）作统计汇总\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sex        F                                 M                            \\\n",
      "Age       11     12    13     14      15    11          12    13      14   \n",
      "Height  51.3  58.05  60.9  63.55   64.50  57.5   60.366667  62.5   66.25   \n",
      "Weight  50.5  80.75  91.0  96.25  112.25  85.0  103.500000  84.0  107.50   \n",
      "\n",
      "Sex                    \n",
      "Age         15     16  \n",
      "Height   66.75   72.0  \n",
      "Weight  122.50  150.0  \n"
     ]
    }
   ],
   "source": [
    "Table3 = pd.pivot_table(student, values=['Height','Weight'], columns=['Sex','Age'])\n",
    "print(Table3)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "很显然这样的结果并不像Excel中预期的那样，该如何变成列联表的形式的？很简单，只需将结果进行非堆叠操作（unstack）即可："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Sex  Age        \n",
      "F    11   Height     51.300000\n",
      "          Weight     50.500000\n",
      "     12   Height     58.050000\n",
      "          Weight     80.750000\n",
      "     13   Height     60.900000\n",
      "          Weight     91.000000\n",
      "     14   Height     63.550000\n",
      "          Weight     96.250000\n",
      "     15   Height     64.500000\n",
      "          Weight    112.250000\n",
      "M    11   Height     57.500000\n",
      "          Weight     85.000000\n",
      "     12   Height     60.366667\n",
      "          Weight    103.500000\n",
      "     13   Height     62.500000\n",
      "          Weight     84.000000\n",
      "     14   Height     66.250000\n",
      "          Weight    107.500000\n",
      "     15   Height     66.750000\n",
      "          Weight    122.500000\n",
      "     16   Height     72.000000\n",
      "          Weight    150.000000\n",
      "dtype: float64\n"
     ]
    }
   ],
   "source": [
    "Table4 = pd.pivot_table(student, values=['Height','Weight'], columns=['Sex','Age']).unstack()\n",
    "print(Table4)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**使用多个聚合函数**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "             mean         median                std           \n",
      "Sex             F       M      F       M          F          M\n",
      "Height  60.588889   63.91   62.5   64.15   5.018328   4.937937\n",
      "Weight  90.111111  108.95   90.0  107.25  19.383914  22.727186\n"
     ]
    }
   ],
   "source": [
    "Table5 = pd.pivot_table(student, values=['Height','Weight'], columns=['Sex'],aggfunc=[np.mean,np.median,np.std])\n",
    "print(Table5)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "---\n",
    "<a id='Chapter8'></a>\n",
    "## 8. 多层索引的使用\n",
    "[回目录](#HOME)\n",
    "\n",
    "最后我们再来讲讲pandas中的一个重要功能，那就是多层索引。在序列中它可以实现在一个轴上拥有多个索引，就类似于Excel中常见的这种形式：\n",
    "\n",
    "![GitHub](http://aliyuntianchipublic.cn-hangzhou.oss-pub.aliyun-inc.com/public/files/image/null/1532666318314_DbhIks5zfc.jpg)\n",
    "\n",
    "对于这样的数据格式有什么好处呢？pandas可以帮我们实现用低维度形式处理高维数数据，这里举个例子也许你就能明白了："
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "a  1    1\n",
      "   2    2\n",
      "   3    3\n",
      "b  1    4\n",
      "   2    5\n",
      "c  3    6\n",
      "   1    7\n",
      "d  2    8\n",
      "   3    9\n",
      "dtype: int64\n"
     ]
    }
   ],
   "source": [
    "# Series的层次化索引，索引是一个二维数组，相当于两个索引决定一个值\n",
    "# 有点类似于DataFrame的行索引和列索引\n",
    "s = pd.Series(np.arange(1,10),index=[[\"a\",\"a\",\"a\",\"b\",\"b\",\"c\",\"c\",\"d\",\"d\"],[1,2,3,1,2,3,1,2,3]])\n",
    "print(s)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "MultiIndex([('a', 1),\n",
      "            ('a', 2),\n",
      "            ('a', 3),\n",
      "            ('b', 1),\n",
      "            ('b', 2),\n",
      "            ('c', 3),\n",
      "            ('c', 1),\n",
      "            ('d', 2),\n",
      "            ('d', 3)],\n",
      "           )\n"
     ]
    }
   ],
   "source": [
    "print(s.index)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "1    1\n",
      "2    2\n",
      "3    3\n",
      "dtype: int64\n",
      "1\n",
      "1    1\n",
      "3    3\n",
      "dtype: int64\n",
      "a  1    1\n",
      "   2    2\n",
      "   3    3\n",
      "c  3    6\n",
      "   1    7\n",
      "dtype: int64\n",
      "b  1    4\n",
      "   2    5\n",
      "c  3    6\n",
      "   1    7\n",
      "d  2    8\n",
      "   3    9\n",
      "dtype: int64\n",
      "     1    2    3\n",
      "a  1.0  2.0  3.0\n",
      "b  4.0  5.0  NaN\n",
      "c  7.0  NaN  6.0\n",
      "d  NaN  8.0  9.0\n"
     ]
    }
   ],
   "source": [
    "#选取外层索引为a的数据\n",
    "print(s['a'])\n",
    "#选取外层索引为a和内层索引为1的数据\n",
    "print(s['a',1])\n",
    "#选取外层索引为a和内层索引为1,3的数据\n",
    "print(s['a'][[1,3]])\n",
    "#层次化索引的切片，包括右端的索引\n",
    "print(s[['a','c']])\n",
    "print(s['b':'d'])\n",
    "#通过unstack方法可以将Series变成一个DataFrame\n",
    "#数据的类型以及数据的输出结构都变成了DataFrame，对于不存在的位置使用NaN填充\n",
    "print(s.unstack())"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "**DataFrame的层次化索引**"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead tr th {\n",
       "        text-align: left;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th colspan=\"6\" halign=\"left\">模拟考</th>\n",
       "      <th colspan=\"6\" halign=\"left\">正式考</th>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>数学</th>\n",
       "      <th>语文</th>\n",
       "      <th>英语</th>\n",
       "      <th>物理</th>\n",
       "      <th>化学</th>\n",
       "      <th>生物</th>\n",
       "      <th>数学</th>\n",
       "      <th>语文</th>\n",
       "      <th>英语</th>\n",
       "      <th>物理</th>\n",
       "      <th>化学</th>\n",
       "      <th>生物</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"4\" valign=\"top\">期中</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">雷军</th>\n",
       "      <th>测试一</th>\n",
       "      <td>34</td>\n",
       "      <td>65</td>\n",
       "      <td>44</td>\n",
       "      <td>64</td>\n",
       "      <td>5</td>\n",
       "      <td>63</td>\n",
       "      <td>72</td>\n",
       "      <td>143</td>\n",
       "      <td>56</td>\n",
       "      <td>100</td>\n",
       "      <td>125</td>\n",
       "      <td>46</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>109</td>\n",
       "      <td>25</td>\n",
       "      <td>137</td>\n",
       "      <td>100</td>\n",
       "      <td>100</td>\n",
       "      <td>19</td>\n",
       "      <td>122</td>\n",
       "      <td>84</td>\n",
       "      <td>134</td>\n",
       "      <td>15</td>\n",
       "      <td>92</td>\n",
       "      <td>83</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">李斌</th>\n",
       "      <th>测试一</th>\n",
       "      <td>36</td>\n",
       "      <td>5</td>\n",
       "      <td>10</td>\n",
       "      <td>97</td>\n",
       "      <td>77</td>\n",
       "      <td>43</td>\n",
       "      <td>131</td>\n",
       "      <td>69</td>\n",
       "      <td>15</td>\n",
       "      <td>107</td>\n",
       "      <td>74</td>\n",
       "      <td>89</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>146</td>\n",
       "      <td>113</td>\n",
       "      <td>55</td>\n",
       "      <td>15</td>\n",
       "      <td>139</td>\n",
       "      <td>135</td>\n",
       "      <td>17</td>\n",
       "      <td>123</td>\n",
       "      <td>142</td>\n",
       "      <td>99</td>\n",
       "      <td>111</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"4\" valign=\"top\">期末</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">雷军</th>\n",
       "      <th>测试一</th>\n",
       "      <td>92</td>\n",
       "      <td>29</td>\n",
       "      <td>147</td>\n",
       "      <td>51</td>\n",
       "      <td>37</td>\n",
       "      <td>13</td>\n",
       "      <td>134</td>\n",
       "      <td>84</td>\n",
       "      <td>62</td>\n",
       "      <td>20</td>\n",
       "      <td>119</td>\n",
       "      <td>44</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>35</td>\n",
       "      <td>77</td>\n",
       "      <td>91</td>\n",
       "      <td>106</td>\n",
       "      <td>19</td>\n",
       "      <td>105</td>\n",
       "      <td>19</td>\n",
       "      <td>18</td>\n",
       "      <td>10</td>\n",
       "      <td>78</td>\n",
       "      <td>17</td>\n",
       "      <td>38</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">李斌</th>\n",
       "      <th>测试一</th>\n",
       "      <td>70</td>\n",
       "      <td>31</td>\n",
       "      <td>79</td>\n",
       "      <td>144</td>\n",
       "      <td>98</td>\n",
       "      <td>54</td>\n",
       "      <td>110</td>\n",
       "      <td>137</td>\n",
       "      <td>134</td>\n",
       "      <td>45</td>\n",
       "      <td>143</td>\n",
       "      <td>57</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>137</td>\n",
       "      <td>75</td>\n",
       "      <td>37</td>\n",
       "      <td>97</td>\n",
       "      <td>138</td>\n",
       "      <td>123</td>\n",
       "      <td>27</td>\n",
       "      <td>26</td>\n",
       "      <td>91</td>\n",
       "      <td>83</td>\n",
       "      <td>74</td>\n",
       "      <td>31</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "           模拟考                           正式考                        \n",
       "            数学   语文   英语   物理   化学   生物   数学   语文   英语   物理   化学  生物\n",
       "期中 雷军 测试一   34   65   44   64    5   63   72  143   56  100  125  46\n",
       "      测试二  109   25  137  100  100   19  122   84  134   15   92  83\n",
       "   李斌 测试一   36    5   10   97   77   43  131   69   15  107   74  89\n",
       "      测试二  146  113   55   15  139  135   17  123  142   99  111   9\n",
       "期末 雷军 测试一   92   29  147   51   37   13  134   84   62   20  119  44\n",
       "      测试二   35   77   91  106   19  105   19   18   10   78   17  38\n",
       "   李斌 测试一   70   31   79  144   98   54  110  137  134   45  143  57\n",
       "      测试二  137   75   37   97  138  123   27   26   91   83   74  31"
      ]
     },
     "execution_count": 19,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data = pd.DataFrame(np.random.randint(0,150,size=(8,12)),\n",
    "               columns = pd.MultiIndex.from_product([['模拟考','正式考'],\n",
    "                                                   ['数学','语文','英语','物理','化学','生物']]),\n",
    "               index = pd.MultiIndex.from_product([['期中','期末'],\n",
    "                                                   ['雷军','李斌'],\n",
    "                                                  ['测试一','测试二']]))\n",
    "data"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>语文</th>\n",
       "      <th>数学</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"4\" valign=\"top\">期中</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">雷军</th>\n",
       "      <th>测试一</th>\n",
       "      <td>65</td>\n",
       "      <td>34</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>25</td>\n",
       "      <td>109</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">李斌</th>\n",
       "      <th>测试一</th>\n",
       "      <td>5</td>\n",
       "      <td>36</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>113</td>\n",
       "      <td>146</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"4\" valign=\"top\">期末</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">雷军</th>\n",
       "      <th>测试一</th>\n",
       "      <td>29</td>\n",
       "      <td>92</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>77</td>\n",
       "      <td>35</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">李斌</th>\n",
       "      <th>测试一</th>\n",
       "      <td>31</td>\n",
       "      <td>70</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>75</td>\n",
       "      <td>137</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            语文   数学\n",
       "期中 雷军 测试一   65   34\n",
       "      测试二   25  109\n",
       "   李斌 测试一    5   36\n",
       "      测试二  113  146\n",
       "期末 雷军 测试一   29   92\n",
       "      测试二   77   35\n",
       "   李斌 测试一   31   70\n",
       "      测试二   75  137"
      ]
     },
     "execution_count": 20,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['模拟考'][['语文','数学']]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "34\n"
     ]
    }
   ],
   "source": [
    "print(data.loc['期中','雷军','测试一']['模拟考','数学'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模拟考  数学     34\n",
      "     语文     65\n",
      "     英语     44\n",
      "     物理     64\n",
      "     化学      5\n",
      "     生物     63\n",
      "正式考  数学     72\n",
      "     语文    143\n",
      "     英语     56\n",
      "     物理    100\n",
      "     化学    125\n",
      "     生物     46\n",
      "Name: (期中, 雷军, 测试一), dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(data.loc['期中','雷军','测试一'])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "模拟考  数学     34\n",
      "     语文     65\n",
      "     英语     44\n",
      "     物理     64\n",
      "     化学      5\n",
      "     生物     63\n",
      "正式考  数学     72\n",
      "     语文    143\n",
      "     英语     56\n",
      "     物理    100\n",
      "     化学    125\n",
      "     生物     46\n",
      "Name: (期中, 雷军, 测试一), dtype: int64\n"
     ]
    }
   ],
   "source": [
    "print(data.iloc[0])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th></th>\n",
       "      <th>数学</th>\n",
       "      <th>语文</th>\n",
       "      <th>英语</th>\n",
       "      <th>物理</th>\n",
       "      <th>化学</th>\n",
       "      <th>生物</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th rowspan=\"4\" valign=\"top\">期中</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">雷军</th>\n",
       "      <th>测试一</th>\n",
       "      <td>72</td>\n",
       "      <td>143</td>\n",
       "      <td>56</td>\n",
       "      <td>100</td>\n",
       "      <td>125</td>\n",
       "      <td>46</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>122</td>\n",
       "      <td>84</td>\n",
       "      <td>134</td>\n",
       "      <td>15</td>\n",
       "      <td>92</td>\n",
       "      <td>83</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">李斌</th>\n",
       "      <th>测试一</th>\n",
       "      <td>131</td>\n",
       "      <td>69</td>\n",
       "      <td>15</td>\n",
       "      <td>107</td>\n",
       "      <td>74</td>\n",
       "      <td>89</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>17</td>\n",
       "      <td>123</td>\n",
       "      <td>142</td>\n",
       "      <td>99</td>\n",
       "      <td>111</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"4\" valign=\"top\">期末</th>\n",
       "      <th rowspan=\"2\" valign=\"top\">雷军</th>\n",
       "      <th>测试一</th>\n",
       "      <td>134</td>\n",
       "      <td>84</td>\n",
       "      <td>62</td>\n",
       "      <td>20</td>\n",
       "      <td>119</td>\n",
       "      <td>44</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>19</td>\n",
       "      <td>18</td>\n",
       "      <td>10</td>\n",
       "      <td>78</td>\n",
       "      <td>17</td>\n",
       "      <td>38</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th rowspan=\"2\" valign=\"top\">李斌</th>\n",
       "      <th>测试一</th>\n",
       "      <td>110</td>\n",
       "      <td>137</td>\n",
       "      <td>134</td>\n",
       "      <td>45</td>\n",
       "      <td>143</td>\n",
       "      <td>57</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>测试二</th>\n",
       "      <td>27</td>\n",
       "      <td>26</td>\n",
       "      <td>91</td>\n",
       "      <td>83</td>\n",
       "      <td>74</td>\n",
       "      <td>31</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "            数学   语文   英语   物理   化学  生物\n",
       "期中 雷军 测试一   72  143   56  100  125  46\n",
       "      测试二  122   84  134   15   92  83\n",
       "   李斌 测试一  131   69   15  107   74  89\n",
       "      测试二   17  123  142   99  111   9\n",
       "期末 雷军 测试一  134   84   62   20  119  44\n",
       "      测试二   19   18   10   78   17  38\n",
       "   李斌 测试一  110  137  134   45  143  57\n",
       "      测试二   27   26   91   83   74  31"
      ]
     },
     "execution_count": 24,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "data['正式考']"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.5"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}
